<?php

namespace App\Http\Controllers\Admin;

use App\Exports\InspectionExport;
use App\Http\Filters\InspectionFilter;
use App\Imports\InspectionImport;
use App\Models\Housings;
use App\Models\Inspection;
use App\Http\Requests\InspectionRequest;
use App\Http\Resources\InspectionResource;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
class InspectionController extends Controller
{
    public function index(InspectionFilter $filter)
    {
        $inspections = Inspection::query()->with('housings')
            ->filter($filter)
            ->paginate();
        return $this->ok(InspectionResource::collection($inspections));
    }

    public function create()
    {
        return $this->ok();
    }

    public function store(InspectionRequest $request)
    {
        $inputs = $request->validated();
        $inspection = Inspection::create($inputs);
        return $this->created(InspectionResource::make($inspection));
    }

    public function edit(Request $request, Inspection $inspection,$id)
    {
        $report = Inspection::findOrFail($id);
        return $this->ok(InspectionResource::make($report)->additional($this->formData($report)));
    }
    protected function formData($report)
    {
        $housings = Housings::query()
            ->where('id',$report['housings_id'])
            ->select(['id', 'hou_address','housings_num'])
            ->orderByDesc('id')
            ->first();
        return compact('housings');
    }

    public function update(InspectionRequest $request, Inspection $inspection,$id)
    {
        $inputs = $request->validated();
        $report = Inspection::findOrFail($id);
        $report->update($inputs);
        return $this->created(InspectionResource::make($report));
    }

    public function destroy(Inspection $inspection)
    {
        $inspection->delete();
        return $this->noContent();
    }

    public function export()
    {
        return Excel::download(new InspectionExport, '巡检问题.xlsx');
    }

    public function import(Request $request)
    {
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls',
        ]);
        $file = $request->file('file');
        try {
            Excel::import(new InspectionImport, $file);
            return back()->with('success', 'Excel 文件导入成功！');
        } catch (\Exception $e) {
            return back()->withErrors(['file' => '导入失败，请检查文件格式和内容是否正确。']);
        }
    }
}
